package test2.guava;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;

public class CacheTest2 {
	
	LoadingCache<Integer, String> cache = CacheBuilder
			.newBuilder()
			.expireAfterAccess(5L, TimeUnit.MINUTES) //5分钟后缓存失效
			.maximumSize(3)
			.recordStats()
			.removalListener(new RemovalListener<Integer, String>() {
				@Override
				public void onRemoval(RemovalNotification<Integer, String> notification) {
					System.out.println("[" + notification.getKey() + "--->" +  notification.getValue() + "]被移除...");
					System.out.println(notification.getCause());
				}
			})
			.build(new CacheLoader<Integer, String>() {
						public String load(Integer key) throws Exception {
							return names.get(key);
						}
					});
	
	List<String> names = Arrays.asList(new String[]{"zhangsan", "lisi", "xiaoming", "fazheng", "zhuge", "fenghuang"});
	
	@Test
	public void test1() throws ExecutionException {
		for(int i=0;i<10;i++) {
			System.out.println(cache.get(new Random().nextInt(5)));
		}
		System.out.println(cache.stats());
	}

}
